package com.urban.pooling.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.urban.pooling.domain.GeoPoint;
import com.urban.pooling.service.google.Directions;

@Service
public class GoogleMapsService {
	private static final Logger LOG = LoggerFactory.getLogger(GoogleMapsService.class);

	public List<GeoPoint> getRouteWaypoints(GeoPoint startPosition, GeoPoint endPosition) {
		String googleRouteResponse = makeRouteRequest(startPosition, endPosition);
		Directions directions = new Directions(googleRouteResponse);
		return directions.getRoutes().get(0).getPath();
		//return getGeoPointsFromRouteResponse(googleRouteResponse);
	}

	private List<GeoPoint> getGeoPointsFromRouteResponse(String googleRouteResponse) {
		JSONObject routeResponseJson = new JSONObject(googleRouteResponse);

		if (!routeResponseJson.isNull("routes")) {
			JSONArray route = routeResponseJson.getJSONArray("routes");

			// Use only the first route
			// for(int k=0;k<route.length(); k++){

			JSONObject routeJson = route.getJSONObject(0);
			return parseRouteJson(routeJson);
			// }
		}
		return new ArrayList<GeoPoint>();
	}

	private List<GeoPoint> parseRouteJson(JSONObject routeJson) {
		return null;
	}

	private String makeRouteRequest(GeoPoint startPosition, GeoPoint endPosition) {
		String url = "http://maps.googleapis.com/maps/api/directions/json?" + "origin=" + startPosition.getLat() + ","
				+ startPosition.getLng() + "&destination=" + endPosition.getLat() + "," + endPosition.getLng()
				+ "&sensor=false&units=metric&mode=driving";
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost httpPost = new HttpPost(url);
			HttpResponse response = httpClient.execute(httpPost, localContext);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String responseBody = EntityUtils.toString(response.getEntity());
				LOG.debug("Route response :" + responseBody);
				return responseBody;
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return null;
	}
}
